package com.module.third.wx

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.lifecycle.*
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import com.module.base.ext.request
import com.module.frame.base.BaseVmVdbActivity
import com.module.third.ThirdUtil
import com.module.third.bean.IThirdType.IShareType
import com.module.third.bean.ThirdAccountBean
import com.module.third.learcloud.lcQuerySingle
import com.module.third.wx.model.WxViewModel
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


class WxUtils(context: Context, scope: CoroutineScope, lifecycle: Lifecycle) : ViewModelStoreOwner {


    //直接去生命周期的作用域
    constructor(context: Context, lifecycle: Lifecycle) : this(
        context,
        lifecycle.coroutineScope,
        lifecycle
    )

    private val api: IWXAPI by lazy {
        WXAPIFactory.createWXAPI(context, WxConfig.WX_APP_ID, true)
    }

    private val context: Context = context
    private val scope: CoroutineScope = scope
    private val lifecycle: Lifecycle = lifecycle

    private val mViewModel: WxViewModel by lazy {
        ViewModelProvider(this).get(WxViewModel::class.java)
    }

    private val mViewModelStore by lazy {////定义ViewModelStore变量
        ViewModelStore()
    }

    init {
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                destroy()
            }
        })
        regToWx(WxConfig.WX_APP_ID)
    }

    private fun regToWx(appId: String) {
        api.registerApp(appId)
    }

    fun login() {
        if (!api.isWXAppInstalled) {
            Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(WxConfig.WX_APP_ID) || TextUtils.isEmpty(WxConfig.WX_SECRET)) {
            getWxAppId()
        } else {
            val req = SendAuth.Req()
            //        req.scope = "snsapi_userinfo,snsapi_friend,snsapi_message,snsapi_contact";
            req.scope = "snsapi_userinfo" //
            req.state = WxConfig.WX_LOGON_STATE
            api.sendReq(req)
        }
    }

    private fun getWxAppId() {
        request({
            val tClass = ThirdAccountBean::class.java
            val query = LCQuery<LCObject>(tClass.simpleName)
            lcQuerySingle(query, tClass)
        }, {
            WxConfig.WX_APP_ID = it?.wxId ?: ""
            WxConfig.WX_SECRET = it?.wxSecret ?: ""
            regToWx(WxConfig.WX_APP_ID)
            login()
        }, {
            Toast.makeText(context, "貌似出了点差错，请稍后重试~", Toast.LENGTH_SHORT).show()
        }, true, scope)
    }

    fun wxPay(
        appId: String,
        partnerId: String,
        prepayId: String,
        nonceStr: String,
        timeStamp: String,
        sign: String
    ) {
        if (!api.isWXAppInstalled) {
            Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show()
            return
        }
        val request = PayReq()
        request.appId = appId
        request.partnerId = partnerId
        request.prepayId = prepayId
        request.packageValue = "Sign=WXPay"
        request.nonceStr = nonceStr
        request.timeStamp = timeStamp
        request.sign = sign
        api.sendReq(request)
    }


    fun share(@IShareType flag: Int, text: String?): Boolean {
        if (!api.isWXAppInstalled) {
            Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show()
            return false
        }
        val textObj = WXTextObject()
        textObj.text = text
        val msg = WXMediaMessage()
        msg.mediaObject = textObj
        msg.description = text
        val req = SendMessageToWX.Req()
        req.transaction = WxCommonUtils.buildTransaction("text")
        req.message = msg
        req.scene =
            if (flag == 0) SendMessageToWX.Req.WXSceneSession else SendMessageToWX.Req.WXSceneTimeline
        return api.sendReq(req)
    }

    //0代表分享到微信好友，1代表分享到朋友圈
    fun shareUrl(
        @IShareType flag: Int,
        webUrl: String?,
        title: String?,
        content: String?,
        @DrawableRes logo: Int
    ) {
        if (!api.isWXAppInstalled) {
            Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show()
            return
        }

        // 初始化一个WXWebpageObject对象
        val webpageObject = WXWebpageObject()
        // 填写网页的url
        webpageObject.webpageUrl = webUrl

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        val msg = WXMediaMessage(webpageObject)
        // 填写网页标题、描述、位图
        msg.title = title
        msg.description = content

        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(
            WxCommonUtils.drawableBitmapOnWhiteBg(
                context,
                BitmapFactory.decodeResource(context.resources, logo)
            )
        )

        // 构造一个Req
        val req = SendMessageToWX.Req()
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = WxCommonUtils.buildTransaction("text")

        // 上文的WXMediaMessage对象
        req.message = msg
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene =
            if (flag == 0) SendMessageToWX.Req.WXSceneSession else SendMessageToWX.Req.WXSceneTimeline

        // 向微信发送请求
        api.sendReq(req)
    }

    //0代表分享到微信好友，1代表分享到朋友圈
    fun shareImg(@IShareType flag: Int, bitmap: Bitmap?) {
        // 检查手机或者模拟器是否安装了微信
        if (!api.isWXAppInstalled) {
            Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show()
            return
        }
        val imgObj = WXImageObject(ThirdUtil.compressBitmap(bitmap, 300f))
        val msg = WXMediaMessage()
        msg.mediaObject = imgObj
        //构造一个Req
        val req = SendMessageToWX.Req()
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = "img" + System.currentTimeMillis()
        req.message = msg
        req.scene =
            if (flag == 0) SendMessageToWX.Req.WXSceneSession else SendMessageToWX.Req.WXSceneTimeline
        //req.userOpenId = getOpenId();
        //调用api接口，发送数据到微信
        api.sendReq(req)
    }

    //jump微信app界面
    fun jumpWx(context: Context) {
        try {
            val lan = context.packageManager.getLaunchIntentForPackage("com.tencent.mm")
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.component = lan!!.component
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun destroy() {
        viewModelStore.clear()
    }

    override fun getViewModelStore(): ViewModelStore {
        return mViewModelStore
    }

}